import React, {useState} from 'react';
import {Category,Product} from "./types";
import {useMutation} from '@apollo/react-hooks';
import {ADD_PRODUCT,PRODUCTS} from "./query";

interface Props {
  categories: Array<Category>
}

function AddProduct(props: Props) {
  const [product, setProduct] = useState<Product>({name: props.categories[0].name, categoryId: props.categories[0].id});
  const [addProduct] = useMutation(ADD_PRODUCT);

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    addProduct({
      variables: product, refetchQueries: [{
        query: PRODUCTS /** 会自动刷新组件*/
      }]
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <div className="form-group">
        <label htmlFor="">产品名称</label>
        <input type="text" value={product.name}
               onChange={event => setProduct({...product, name: event.target.value})}/>
      </div>
      <div className="form-group">
        <label htmlFor="">产品分类</label>
        <select value={product.categoryId}
                className="form-control"
                onChange={event => setProduct({...product, categoryId: event.target.value})}>
          {
            props.categories.map((item: Category,index) => (
              <option value={item.id}>{item.name}</option>
            ))
          }
        </select>
      </div>
      <div className="form-group">
        <input type="submit" className="btn btn-primary"/>
      </div>
    </form>
  );
}

export default AddProduct;
